package com.cpr.demo.service;

import com.cpr.demo.constant.QueueConstant;
import com.cpr.demo.mycraft.mq.redis.RedisMessageQueueManager;
import com.cpr.demo.service.PersonService;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Chen Panrui
 * created at 2021/10/9 16:04
 * Q: 为什么有这个类？
 * A: 测试single-message的redis的消息队列是否有问题
 */
@Service("personService1")
@Slf4j
public class PersonCacheServiceImpl implements PersonService, InitializingBean {

    private final Map<String,String> cache = Maps.newHashMapWithExpectedSize(25);
    @Autowired
    @Qualifier("singleRedisMQ")
    private RedisMessageQueueManager redisMessageQueueManager;

    @Override
    public String getInfo(String whom) {
        synchronized (cache){
            return cache.get(whom);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 订阅 某个 队列
        redisMessageQueueManager.subscribe(QueueConstant.PERSON1_QUEUE, message -> {
            log.info(">>>开始处理消费逻辑message={}", message);
            initCache(message);
        });
    }

    private void initCache(String message){
        synchronized (cache){
            cache.clear();
            cache.put("cpr", String.format("I am %s", message));
        }
    }
}
